<template>
	<!-- pages/cart/cart.wxml -->
	<view class="container" :style="'padding-bottom:' + (proList.length > 0 ? '90rpx' : '0')">
		<view v-if="proList.length > 0" class="tabBar end">
			<view v-if="action" @tap="edit" class="edit">编辑</view>
			<view v-else @tap="complete" class="edit">完成</view>
		</view>
		<view class="cartList">
			<view v-if="proList.length > 0">
				<view class="v-center between stretch item" v-for="(item, idx) in proList" :key="idx">
					<view class="radiobox algin" @tap="radioChange" :data-index="idx" :data-id="item.Fid">
						<view v-if="!item.disabled" class="radio_btn algin" style="background: #ddd; color: #ddd">
							<text class="icon iconfont icon-duihao"></text>
						</view>
						<view v-else class="radio_btn algin" :style="'background:' + (item.checked ? color : '#fff')">
							<text class="icon iconfont icon-duihao"></text>
						</view>
					</view>

					<view class="pro-content between">
						<view class="pro-img" @tap="radioChange" :data-index="idx" :data-id="item.Fid">
							<image :src="item.Faid == 0 ? item.Sku.Fimg : item.Time.Fimg"></image>
						</view>
						<view class="pro-context">
							<view @tap="link" :data-index="idx" :data-id="item.Fid" class="pro-name">
								{{ item.Faid == 0 ? item.Sku.Fsummary : item.Time.Fsummary }}
							</view>
							<view @tap="link" :data-index="idx" :data-id="item.Fid" class="pro-info">{{ item.Fattr }}
							</view>
							<view class="pro-price v-center between">
								<text @tap="link" :data-index="idx" :data-id="item.Fid" class="price">
									{{ '￥' + (item.Faid == 0 ? item.Sku.Fsaleprice : item.Time.Fsaleprice) + ' ' + item.Fmsg }}
								</text>
								<view v-if="!item.disabled" @tap="delPro" class="delpro" :data-id="item.Fid">删除</view>
								<view v-else class="pro-num algin">
									<text @tap="changeNum" :data-max="item.maxnum" :data-num="item.Fnum"
										:data-id="item.Fid" data-type="sub" class="changeicon sub">-</text>
									<input type="number" pattern="\d*" :data-max="item.maxnum" :data-id="item.Fid"
										@blur="inputNum" :value="item.Fnum" />
									<text @tap="changeNum" :data-max="item.maxnum" :data-id="item.Fid"
										:data-num="item.Fnum" data-type="add" class="changeicon add">+</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else>
				<view @tap="backhome" class="blank">
					<view class="algin">
						<image mode="widthFix" class="noImg" src="/static/file/images/nocart.png"></image>
					</view>
					<view class="no_msg algin">暂无商品，快去购物吧~~~</view>
				</view>
			</view>
			<!-- 推荐列表 -->
			<view v-if="recommend.length > 0">
				<view class="v-center hv-center titileBar">
					<image mode="widthFix" src="/static/file/images/c_love.png"></image>
				</view>
				<view class="pro_list wrap between">
					<view class="pro_item" v-for="(item, idx) in recommend" :key="idx">
						<navigator
							:url="'/pages/proDetail/proDetail?Ftypeid=' + item.Fid + '&Ftype=3&Fshopcart=0&typeId=0'"
							hover-class="none">
							<view class="pro_pic">
								<image mode="aspectFill" :src="item.Fhimg"></image>
							</view>
							<view class="pro_text">
								<view class="pro_name">【{{ item.Fbrand }}】 {{ item.Fsummary }}</view>
								<view class="pro_price v-center between">
									<text class="dis_price">￥{{ item.Flowprice }}</text>
									<text class="buynum">{{ item.Fpersonnum }}/笔购买</text>
								</view>
							</view>
							<!-- <view class="end v-center buy_bar">
              <view class="buy_btn">立即购买</view>
            </view> -->
						</navigator>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部 -->
		<block v-if="proList.length > 0">
			<view v-if="action" class="accountBar between v-center">
				<view @tap="selectAll" class="selectAll v-center around">
					<view class="radio_btn algin" :style="'background:' + (selall ? color : '#fff')">
						<text class="icon iconfont icon-duihao"></text>
					</view>
					<text>全选</text>
				</view>
				<view class="algin">
					<text>总计：</text>
					<text class="totalmoney">￥{{ totalmoney }}</text>
				</view>
				<view :class="'countBtn ' + selectPro.length"
					@tap="parseEventDynamicCode($event, selectPro.length > 0 ? 'account' : '')"
					:style="'background:' + (selectPro.length > 0 ? color : '#A6A6A6')">
					结算
				</view>
			</view>
			<view v-else class="accountBar between v-center">
				<view @tap="selectAll" class="selectAll v-center around">
					<view class="radio_btn algin" :style="'background:' + (selall ? color : '#fff')">
						<text class="icon iconfont icon-duihao"></text>
					</view>
					<text>全选</text>
				</view>
				<view class="delBtn" @tap="delCart" :style="'background:' + color">删除</view>
			</view>
		</block>
	</view>
</template>

<script>
	// pages/cart/cart.js
	var util = require('../../utils/util.js');
	var api = require('../../utils/prom.js');
	export default {
		data() {
			return {
				color: app.globalData.color,
				proList: [],
				totalmoney: 0,
				action: true,
				selectPro: [],
				selall: false,
				recommend: [],
				hasLogin: false
			};
		}
		/**
		 * 生命周期函数--监听页面显示
		 */
		,
		onShow: function() {
			this.onShowClone3389();
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {
			this.onShowClone3389({});
			uni.stopPullDownRefresh();
		},
		onHide: function() { 
		}, 
		methods: {
			/**
			 * 生命周期函数--监听页面显示
			 */
			onShowClone3389: function() {
				this.searchProList();
				this.recommendList();
			},

			//购物车商品列表
			searchProList: function() {
				var that = this;
				that.proList = [];
				that.totalmoney = 0;
				that.action = true;
				that.selectPro = [];
				that.selall = false;
				var param = {
					token: uni.getStorageSync('token')
				};
				api.request('SpShopCart', 'get', param, function(res) {
					var proList = [];
					res.data.Row.map(function(item, index) {
						if (null == item.Time) {
							if (!util.isEmpty(item.Sku.Fattr)) {
								var Fattr = '';
								var arr = JSON.parse(item.Sku.Fattr);
								for (var i in arr) {
									var row = arr[i];
									Fattr += row.Fattr + ':' + row.Fvalue + '；';
								}
								item.Fattr = Fattr;
							}
							item.disabled = true;
							item.Fmsg = '';
							if (item.Sku.Fstocknum <= 0) {
								item.Fmsg = '库存不足';
								item.disabled = false;
							}
							if (item.Sku.Fstocknum <= 5) {
								item.Fmsg = '即将售罄';
							}
							if (Number(item.Sku.Fsaleprice) < Number(item.Fprice)) {
								item.Fmsg += '降价';
							}
							item.maxnum = item.Sku.Fstocknum;
						} else {
							if (!util.isEmpty(item.Time.Fattr)) {
								var Fattr = '';
								var arr = JSON.parse(item.Sku.Fattr);
								for (var i in arr) {
									var row = arr[i];
									Fattr += row.Fattr + ':' + row.Fvalue + '；';
								}
								item.Fattr = Fattr;
							}
							item.Fmsg = '';
							item.disabled = true;
							if (item.Item.Fstocknum <= 0) {
								item.disabled = false;
								item.Fmsg = '库存不足';
							}
							if (item.Item.Ftsatus == 2) {
								item.disabled = false;
							}
							if (item.Item.Fstocknum <= 5) {
								item.Fmsg = '即将售罄';
							}
							if (Number(item.Item.Fsaleprice) < Number(item.Fprice)) {
								item.Fmsg += '已降价';
							}
							item.maxnum = Number(item.Time.Ftotal) - Number(item.Fsalenum);
						}
						proList.push(item);
					});
					that.proList = proList;

					console.log(proList);
				});
			},

			//推荐列表
			recommendList: function() {
				var that = this;
				var param = {
					token: uni.getStorageSync('token')
				};
				api.requestAll('SpShopAd', 'get', param, function(res) {
					console.log(res);
					that.recommend = res.data.Rows;
				});
			},

			link: function(e) {
				var proList = this.proList;
				var id = e.currentTarget.dataset.index;
				var item = proList[id];
				if (item.Faid == 0) {
					var url = '/pages/proDetail/proDetail?Ftype=3&Ftypeid=' + item.Fpid;
					uni.navigateTo({
						url: url
					});
				} else {
					var url = '/pages/proDetail/proDetail?Ftype=4&Ftypeid=' + item.Faid;
					uni.navigateTo({
						url: url
					});
				}
			},

			//加或者减少数量
			changeNum: function(e) {
				var that = this;
				var type = e.currentTarget.dataset.type;
				var id = e.currentTarget.dataset.id;
				var num = parseInt(e.currentTarget.dataset.num);
				var max = parseInt(e.currentTarget.dataset.max);
				if (type == 'add') {
					num += 1;
					if (num > max) {
						uni.showToast({
							icon: 'none',
							title: '您已超出最大限额'
						});
					} else {
						that.editNum(id, num);
					}
				} else {
					if (num > 1) {
						num -= 1;
						that.editNum(id, num);
					} else {
						that.delCart(id);
					}
				}
			},

			//输入数量
			inputNum: function(e) {
				var that = this;
				var num = parseInt(e.detail.value);
				var id = e.currentTarget.dataset.id;
				var max = parseInt(e.currentTarget.dataset.max);
				if (num > max) {
					uni.showModal({
						title: '提示',
						content: '您输入数量已超出最大限额，该商品您最多可买' + max + '件',
						success: function(res) {
							if (res.confirm) {
								that.editNum(id, max);
							}
						}
					});
				} else {
					if (num >= 1) {
						that.editNum(id, num);
					} else {
						that.delCart(id);
					}
				}
			},

			//修改数量
			editNum: function(id, num) {
				var that = this;
				var param = {
					Fid: id,
					Fnum: num
				};
				var url = 'SpShopCart?token=' + uni.getStorageSync('token') + '&action=edit';
				api.request(url, 'Post', param, function(res) {
					var alldata = that.proList;
					var seldata = that.selectPro;
					alldata.map(function(item, index) {
						if (item.Fid == id) {
							item.Fnum = num;
						}
					});
					if (seldata.length > 0) {
						for (var i = seldata.length - 1; i >= 0; i--) {
							if (util.isEmpty(seldata[i])) {
								seldata.splice(i, 1);
							}
							if (!seldata[i].disabled) {
								seldata.splice(i, 1);
							}
						}
						var money = 0;
						seldata.map(function(val, i) {
							if (val.Fid == id) {
								val.Fnum = num;
							}
							console.log(val);
							if (val.Sku != null) {
								money += parseFloat(val.Sku.Fsaleprice) * parseFloat(val.Fnum);
							} else {
								money += parseFloat(val.Time.Fsaleprice) * parseFloat(val.Fnum);
							}
						});
						that.totalmoney = parseFloat(money).toFixed(2);
					}

					that.proList = alldata;
					that.selectPro = seldata;

				});
			},

			//单个删除某个商品
			delPro: function(e) {
				var that = this;
				var id = e.currentTarget.dataset.id;
				that.delCart(id);
			},

			//删除购物车
			delCart: function(id) {
				var that = this;
				var arr = [];
				var ids = '';
				var selectp = that.selectPro;
				selectp.map(function(it, idx) {
					if ((it == undefined) | (it == null)) {
						selectp.splice(idx, 1);
					}
				});
				if (selectp.length > 0) {
					selectp.map(function(item) {
						arr.push(item.Fid);
					});
					ids = arr.join(',');
				}
				console.log(id, ids);
				console.log(typeof id == 'string' ? id : ids);
				if (typeof id == 'string' || selectp.length > 0) {
					uni.showModal({
						title: '提示',
						content: '确定要移除所选商品？',
						success: function(res) {
							if (res.confirm) {
								if (typeof id == 'string') {
									var sid = id;
								} else {
									var sid = ids;
								}
								var url = 'SpShopCart?token=' + uni.getStorageSync('token') + '&ids=' +
									sid;
								api.request(url, 'post', {}, function(res) {
									that.searchProList();
								});
							}
						}
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: '请选择商品！'
					});
				}
			},

			//点击编辑
			edit: function() {
				var that = this;
				var status = that.action;
				that.action: !status;
			},

			complete: function() {
				var that = this;
				var status = that.action;
				that.action: !status;
			},

			//选择单选
			radioChange: function(e) {
				var that = this;
				var index = e.currentTarget.dataset.index;
				var id = e.currentTarget.dataset.id;
				var selectp = that.selectPro;
				var allp = that.proList;
				var checked = allp[index].checked;
				var total = 0;
				console.log(checked);
				if (selectp.length > 0) {
					for (var i = selectp.length - 1; i >= 0; i--) {
						if ((selectp[i] == undefined) | (selectp[i] == null)) {
							selectp.splice(i, 1);
						}
						if (selectp[i] && selectp[i].Ftypedesc) {
							if (!selectp[i].disabled) {
								selectp.splice(i, 1);
							}
						}
					}
				}
				if (checked) {
					//取消选中
					selectp.map(function(item, index) {
						if (item.Fid == id) {
							selectp.splice(index, 1);
						}
					});
				} else {
					//选中
					selectp.map(function(item, index) {
						if ((item == undefined) | (item == null)) {
							selectp.splice(index, 1);
						}
					});
					selectp.push(that.proList[index]);
				}
				allp[index].checked = !checked;
				console.log(selectp.length);
				if (selectp.length > 0) {
					selectp.map(function(item) {
						if (item.Faid == 0) {
							var money = parseFloat(item.Sku.Fsaleprice) * parseFloat(item.Fnum);
						} else {
							var money = parseFloat(item.Time.Fsaleprice) * parseFloat(item.Fnum);
						}

						that.totalmoney = parseFloat((total += money)).toFixed(2);

					});
				} else {
					that.totalmoney = 0;
				}
				selectp = util.uniqueArray(selectp, 'Fid');

				that.selectPro = selectp;
				that.proList = allp;
				console.log(that.selectPro);
				console.log(that.proList);
				if (that.selectPro.length == that.proList.length) {
					that.selall = true;
				} else {
					that.selall = false;
				}
			},

			//全选
			selectAll: function() {
				var that = this;
				that.selectPro = [];
				var selectp = that.selectPro;
				var allp = that.proList;
				var checked = that.selall;
				var total = 0;
				console.log(checked);
				if (checked) {
					//取消选中
					allp.map(function(item) {
						item.checked = false;
					});
					that.proList = allp;
					that.selectPro = [];
					that.totalmoney = 0;
					that.selall = false;
				} else {
					//选中
					allp.map(function(item) {
						item.checked = true;
						if (item.Faid == 0) {
							var money = parseFloat(item.Sku.Fsaleprice) * parseFloat(item.Fnum);
						} else {
							var money = parseFloat(item.Time.Fsaleprice) * parseFloat(item.Fnum);
						}
						total += money;
						selectp.push(item);
					});
					for (var i = selectp.length - 1; i >= 0; i--) {
						if ((selectp[i] == undefined) | (selectp[i] == null)) {
							selectp.splice(i, 1);
						}
						if (!selectp[i].disabled) {
							selectp.splice(i, 1);
						}
					}

					that.proList = allp;
					that.selectPro = selectp;
					that.totalmoney = parseFloat(total).toFixed(2);
					that.selall = true;

				}
			},

			//结算
			account: function() {
				var that = this;
				var json = that.selectPro;
				var ids = [];
				for (var i = json.length - 1; i >= 0; i--) {
					if ((json[i] == undefined) | (json[i] == null)) {
						json.splice(i, 1);
					}
					if (!json[i].disabled) {
						json.splice(i, 1);
					}
				}
				json.map(function(item) {
					ids.push(item.Fid);
				});
				console.log(json);
				uni.navigateTo({
					url: '/pages/orderSubmit/orderSubmit?ids=' + ids.join(',') + '&source=2'
				});
			},

			backhome() {
				console.log('占位：函数 backhome 未声明');
			}
		}
	};
</script>
<style>
	@import './cart.css';
</style>